{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b18e2fd9-c211-4969-aa83-517b1f8342fb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Private Key: -----BEGIN RSA PRIVATE KEY-----\n",
      "MIIEowIBAAKCAQEAvdpQGvCxbRfPjE4iGSWzdUU0oTSdJ8O5ceETl/CxvR64BqCh\n",
      "F6cvVHJIji02ZNSzfr3B/dZrq4pWH0Lsskci1QBRHFnRN9d6Qni+ULYtXNGqc7Lr\n",
      "Ik+QJNKNo+1rakdYX2yKKHFkD7MVqGqmzeEHVGtkGMuFG0jxDoZuSdkVr/Qh43IJ\n",
      "akHZOf32SyzyQRU8suZb1Ct/JmV2P+HYmFzK/9CiqHXeMTlaVDuzIXSU9R73KvJG\n",
      "Vcuc/ZdVELdIU+yD9f1nW5RaC4Np2xTAW0rFvdtkyy5SGz5Xi8jNlBHmP3haGYlm\n",
      "F2vnIIi28NYsCMlCH1fNubybGmmuINGGQZX3WwIDAQABAoIBAAEsp2DK0J05F07i\n",
      "agbhF2nt1F+icoKqWDuRhdAYN6qrIBjGok8RCAwKKAC+zPj8luoE224eyts/Y9PR\n",
      "6ioahDKHAJAJRqwq7+UH9fKbSD/ZkOQiGVOuL37K0XjIe6yuwBEzSQpUp1t0VCas\n",
      "6cBr0OJhRr9b0B6+nmpsHcMC85iR3TPl8clIlNfK9fmZgwF0aCHuoy4AQLZekjst\n",
      "WuifaNuIsI1UzL/WWXj+c6UOJ8hQciDotoMikFHCe5FcaEUu3LCHcYurVNVmImAx\n",
      "vzDHdBsJqddfajMwpPJAVoaX0lwVXZb6fGDmQngFa75dEjC3XaWLq5O1aVK7NZUf\n",
      "ktDdv2ECgYEA3AFlM+FU5GGAmpvr+TUs/1keeBpk9FOE/lMOrHK+esuvOLYwh0Ln\n",
      "5eJTGAe4f0s8LM5+SMn44SdDBr24g1+SWTQcEtx+6HPgkLCInqNmrRiKedUPb0cO\n",
      "KMO+iV/2Bp/sqR57p042DUg2L+JebAkCLjzwvF8LAQ2u8BY1bQ4VjS0CgYEA3OoE\n",
      "fXhGix5x/W3oCb7eeKRmnJlyXjqXSTUlgTjOjtPqPLDvMAwCLbDODYUPWoe3pWax\n",
      "kexQVF8I4ant12n6yTqXEXQhKTgoaeWHnfgKnRcMwnz6rhK5+iOlCjCx7hhdUYZf\n",
      "RmFSoNYp0S88HhvqlN5zbw2zU9StLBOJkIdju6cCgYAFIf8zc6lgXqn6cXLS8Jup\n",
      "JXIhiTQbwysSJ+vquA6bnM7susttDHGOmnYn1F5Ikf/IZ9Toa9Xjot/cc2avofYv\n",
      "IJkbE4vebn2pwoSdduB5X14zs3XVucmpx89VMyjxRJ/n3i8yWw/FxY6GFXjwelFT\n",
      "tNZE/s6p6qDPNyVt8usrzQKBgQDORyn4KrXcM4qG9PhlGTfM+N3jvhifyh/3uMuT\n",
      "dQLTNSeUkjZV6/Cgz2YoE6X5h57AsDqAomOD1NWLOcwfiBMnkTD8mC5audhqwWu3\n",
      "4qOueZZtiJverRfBbUUvVbbfNxr0A/+0zS2Fh1S2wl9lUfXiGjE5claPoZgt/vRF\n",
      "41YKIwKBgHgEtVeI3leNf4jfpUraFP4MGbrUsVx26GkN5OPQHIhFdCqballeBnbh\n",
      "IbALk17UU7hgsGmBdgWhVcp+bZJjuX+1FjYvLBYrG8KeaGV5xHHFlRxvoe8MGvTE\n",
      "rzEqWLsHzRI6HgXoExUqa2fC7Ozs6QhHBMFZ0TXualr2vqPg+Iqj\n",
      "-----END RSA PRIVATE KEY-----\n",
      "Public Key: -----BEGIN PUBLIC KEY-----\n",
      "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvdpQGvCxbRfPjE4iGSWz\n",
      "dUU0oTSdJ8O5ceETl/CxvR64BqChF6cvVHJIji02ZNSzfr3B/dZrq4pWH0Lsskci\n",
      "1QBRHFnRN9d6Qni+ULYtXNGqc7LrIk+QJNKNo+1rakdYX2yKKHFkD7MVqGqmzeEH\n",
      "VGtkGMuFG0jxDoZuSdkVr/Qh43IJakHZOf32SyzyQRU8suZb1Ct/JmV2P+HYmFzK\n",
      "/9CiqHXeMTlaVDuzIXSU9R73KvJGVcuc/ZdVELdIU+yD9f1nW5RaC4Np2xTAW0rF\n",
      "vdtkyy5SGz5Xi8jNlBHmP3haGYlmF2vnIIi28NYsCMlCH1fNubybGmmuINGGQZX3\n",
      "WwIDAQAB\n",
      "-----END PUBLIC KEY-----\n",
      "Ciphertext: 5d53ae31397e22d2b4c6c73e1e32da0b55e2e71730d94c6e1df26267b8ac93cc62def990e6578157a9c3026b714a4521551b605d28d2e2db03a2abec9f578db2f95f6e153a78446177e7d3917af50e4d70048f96ef483095cbfe880abb0c59e5fc0691e4427ace0cd6413f54f482463e097eb12cee2cc4f6e55d0bcffc420383be44bca50238e6acf1508335cffc0a5263ee88dfbeef431119f27e95e394a0fa2d9d01464ec12c6aad4056d4fbd24b26c9498e19810fa034beaff5a483d7f91243a728a2d40840fa49f5c3dd7381a84dce88039e0d0f7bcbb858b3f8afdf86d8d62a05b8d6fe2e3e2385798862ffdcb7fea647dd84827b2edf382b590f37764e\n",
      "Decrypted Message: To be encrypted\n"
     ]
    }
   ],
   "source": [
    "import binascii\n",
    "\n",
    "from Crypto.Cipher import PKCS1_OAEP\n",
    "from Crypto.PublicKey import RSA\n",
    "\n",
    "# 生成新的RSA密钥对\n",
    "key = RSA.generate(2048)\n",
    "\n",
    "# 获取私钥和公钥\n",
    "private_key = key.export_key()\n",
    "public_key = key.publickey().export_key()\n",
    "\n",
    "print(\"Private Key:\", private_key.decode(\"utf-8\"))\n",
    "print(\"Public Key:\", public_key.decode(\"utf-8\"))\n",
    "\n",
    "# 使用公钥加密\n",
    "recipient_key = RSA.import_key(public_key)\n",
    "cipher_rsa = PKCS1_OAEP.new(recipient_key)\n",
    "message = \"To be encrypted\".encode(\"utf-8\")\n",
    "ciphertext = cipher_rsa.encrypt(message)\n",
    "print(\"Ciphertext:\", binascii.hexlify(ciphertext).decode(\"utf-8\"))\n",
    "\n",
    "# 使用私钥解密\n",
    "private_key = RSA.import_key(private_key)\n",
    "cipher_rsa = PKCS1_OAEP.new(private_key)\n",
    "decrypted_message = cipher_rsa.decrypt(ciphertext)\n",
    "print(\"Decrypted Message:\", decrypted_message.decode(\"utf-8\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b64c5cf9-10bd-4823-b990-8a3bfac79db3",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "RSA key format is not supported",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mValueError\u001b[39m                                Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[5]\u001b[39m\u001b[32m, line 4\u001b[39m\n\u001b[32m      1\u001b[39m \u001b[38;5;66;03m# 项目中的key\u001b[39;00m\n\u001b[32m      2\u001b[39m \u001b[38;5;66;03m# 使用公钥加密\u001b[39;00m\n\u001b[32m      3\u001b[39m public_key = \u001b[33m\"\u001b[39m\u001b[33mMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJnNwrj4hi/y3CCJu868ghCG5dUj8wZK++RNlTLcXoMmdZWEQ/u02RgD5LyLAXGjLOjbMtC+/J9qofpSGTKSx/MCAwEAAQ==\u001b[39m\u001b[33m\"\u001b[39m.encode(\u001b[33m\"\u001b[39m\u001b[33mutf-8\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m recipient_key = \u001b[43mRSA\u001b[49m\u001b[43m.\u001b[49m\u001b[43mimport_key\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpublic_key\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m      5\u001b[39m cipher_rsa = PKCS1_OAEP.new(recipient_key)\n\u001b[32m      6\u001b[39m message = \u001b[33m\"\u001b[39m\u001b[33mTo be encrypted\u001b[39m\u001b[33m\"\u001b[39m.encode(\u001b[33m\"\u001b[39m\u001b[33mutf-8\u001b[39m\u001b[33m\"\u001b[39m)\n",
      "\u001b[36mFile \u001b[39m\u001b[32m/usr/local/lib/python3.13/site-packages/Crypto/PublicKey/RSA.py:857\u001b[39m, in \u001b[36mimport_key\u001b[39m\u001b[34m(extern_key, passphrase)\u001b[39m\n\u001b[32m    853\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(extern_key) > \u001b[32m0\u001b[39m \u001b[38;5;129;01mand\u001b[39;00m bord(extern_key[\u001b[32m0\u001b[39m]) == \u001b[32m0x30\u001b[39m:\n\u001b[32m    854\u001b[39m     \u001b[38;5;66;03m# This is probably a DER encoded key\u001b[39;00m\n\u001b[32m    855\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m _import_keyDER(extern_key, passphrase)\n\u001b[32m--> \u001b[39m\u001b[32m857\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[33m\"\u001b[39m\u001b[33mRSA key format is not supported\u001b[39m\u001b[33m\"\u001b[39m)\n",
      "\u001b[31mValueError\u001b[39m: RSA key format is not supported"
     ]
    }
   ],
   "source": [
    "# 项目中的key\n",
    "# 使用公钥加密\n",
    "public_key = \"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJnNwrj4hi/y3CCJu868ghCG5dUj8wZK++RNlTLcXoMmdZWEQ/u02RgD5LyLAXGjLOjbMtC+/J9qofpSGTKSx/MCAwEAAQ==\".encode(\n",
    "    \"utf-8\"\n",
    ")\n",
    "recipient_key = RSA.import_key(public_key)\n",
    "cipher_rsa = PKCS1_OAEP.new(recipient_key)\n",
    "message = \"To be encrypted\".encode(\"utf-8\")\n",
    "ciphertext = cipher_rsa.encrypt(message)\n",
    "print(\"Ciphertext:\", binascii.hexlify(ciphertext).decode(\"utf-8\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fee68e08-29f6-462f-93af-ed9059f131aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "key2 = RSA.generate(2048)\n",
    "\n",
    "# 获取私钥和公钥\n",
    "private_key2 = key2.export_key()\n",
    "public_key2 = key2.publickey().export_key()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "e7aabbfb-78fc-4165-b53b-e11aae01be65",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<built-in method decode of bytes object at 0x7f028e09f480>\n"
     ]
    }
   ],
   "source": [
    "print(public_key2.decode)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "9442ab89-1d2d-43ca-a0bc-85d5b364bd1c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "public key:\n",
      " <cryptography.hazmat.bindings._rust.openssl.rsa.RSAPublicKey object at 0xffff70ebeb50>\n",
      "Private Key:\n",
      " -----BEGIN PRIVATE KEY-----\n",
      "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC3pcrrvk0TEfWJ\n",
      "QbSDkZqpYaIi4t8B2CcicSXy4WDvowBJ6tlUTGW88MTDOo7x6uViZJ59Yc0hl+YN\n",
      "V7WZ7l6MP76CuK9GfZwvRsHBAlq4IyPWazph+ML/OOfTM5tjm3s/RNm4QA+I7fHI\n",
      "ymVSIxXLI1sC2JG77e5idl6hvdmJlKcl5M5neApHNNP+4zq9B3n9sVrTgPAbJq4e\n",
      "HQl5IWXy2Ut5V8WxUK/fno8RajaU7FToi/egWYyKn1crGuUO+Fx7J3iDGQxCv2PX\n",
      "TSMYZJLPHYgtXOWY+g3lSRBLsem6eCK0HXH4gFhMBNzS/cjXFzbYOPWwYHouJMPA\n",
      "4clXa7ohAgMBAAECggEARlc8aBtVzi4cy9vc1mAYyzPYNGCNZllyc+C+1k65IFBg\n",
      "te88GuvANCRMWTK+ua5s+cjsY73oIivaM9YaesEweauYvt0aVXebMQh7AgBy2wCq\n",
      "o2Ai1o+/sJ4NPXoQ1JAjHtKySb5PtPTenTfYoyNJH6uFGov1FfRGUHRiPrVG80jT\n",
      "BIpqFNNtD0Kh7yv85hizsoztGgSC5OkEtcBB6tvJZrr3xa7k6vm1ZerbYoOn1oyW\n",
      "gLlHAdDdxKOt0Rzpfq7OsW9T5w6fLumgNBGWLI0RkhAjNn8kAziSTKe8jkYBrv4V\n",
      "1asczoIqGe85vJ5PLyH6jV70We3KKAi61OdBTbgdOQKBgQD6SKgYSM3aQQbfhjDk\n",
      "FuOKoAj2p/8yOTbYvXF0MT5Tf+4r2g3N1gd2mlz5T8zpxi8B8/vJ3B2xmLBFOd64\n",
      "34BHJqo5MuqzJuARafEYLrbV8Aqsx778lTUbOyy4MY/EfuXr+fH4ZTGsWd9scaU1\n",
      "/X2FLC9Cu6HW2ulob2v3mCQCdwKBgQC714gnGvUlnWJNI2XpOCo9XuqANLWu2yVG\n",
      "5fQOZ+m4ARnEDe9HKR0fP4BvQOupLrjyyqExQ32ZK6RaHlMsiUsdYmEWC+2V+kVG\n",
      "K/1wnBjXDJ9l8iBsjMS/s2lJ8lVh8ZgpRJKd2EJI23jN0csAaCRAqPvAH5OUWw4g\n",
      "0vAoODf2JwKBgC7KPoKrubA/z+Uh1SoPDWLxIDvclFzzTUmfwQIT4q8Bj6krDsGY\n",
      "bbTCjvcc8BYUMt2Om1fViseU3/9RHk45mmWy2MfwuOfdMK6Qu73lndDJG3XJse7O\n",
      "hisdGPMmcNYvUxSWmaHyaSLrelVvuY8qYLjw1bUIFu1v54raqbiT/MdpAoGAXsYO\n",
      "MfzN916C/HyBrLvjw/chxfHSQRjco/rdum7/YxFbGKoXMgYyZVO6z2cn/8JNGmLW\n",
      "FW8B7cgxMi7etDfJKFg8t8zo4KTXUuJbCvgXKFl8CwmxBlO36SjyVJbqMXKd3SR1\n",
      "/SHhv7TMLLxO+jORJvabnoHQCigu5qzG8uP6iD0CgYAEKZFv1ALVw8VtiGgL70cC\n",
      "lOhA/qDraBymPTPV/Ry+cbeu6Qu59zfjwr130N12eBeq0OBB6KgOpKGenP7TcKqt\n",
      "fVKlMHiwgVlPUaSvnGr078UsiPOvTMPz+vOTC3jYLNhFY5bbxC+R8itOrW1UXKTS\n",
      "tbCVKHM8gwip0kc+3qxIUQ==\n",
      "-----END PRIVATE KEY-----\n",
      "\n",
      "\n",
      "Public Key:\n",
      " -----BEGIN PUBLIC KEY-----\n",
      "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt6XK675NExH1iUG0g5Ga\n",
      "qWGiIuLfAdgnInEl8uFg76MASerZVExlvPDEwzqO8erlYmSefWHNIZfmDVe1me5e\n",
      "jD++grivRn2cL0bBwQJauCMj1ms6YfjC/zjn0zObY5t7P0TZuEAPiO3xyMplUiMV\n",
      "yyNbAtiRu+3uYnZeob3ZiZSnJeTOZ3gKRzTT/uM6vQd5/bFa04DwGyauHh0JeSFl\n",
      "8tlLeVfFsVCv356PEWo2lOxU6Iv3oFmMip9XKxrlDvhceyd4gxkMQr9j100jGGSS\n",
      "zx2ILVzlmPoN5UkQS7HpungitB1x+IBYTATc0v3I1xc22Dj1sGB6LiTDwOHJV2u6\n",
      "IQIDAQAB\n",
      "-----END PUBLIC KEY-----\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# rsa private & public key encryption in python\n",
    "from cryptography.hazmat.primitives import serialization\n",
    "from cryptography.hazmat.primitives.asymmetric import rsa\n",
    "\n",
    "# Generate a new RSA private key\n",
    "private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)\n",
    "\n",
    "# Derive the public key from the private key\n",
    "public_key = private_key.public_key()\n",
    "\n",
    "# Serialize the private key to PEM format (for storage or sharing)\n",
    "private_key_pem = private_key.private_bytes(\n",
    "    encoding=serialization.Encoding.PEM,\n",
    "    format=serialization.PrivateFormat.PKCS8,\n",
    "    encryption_algorithm=serialization.NoEncryption(),  # Can be encrypted with a password\n",
    ")\n",
    "\n",
    "# Serialize the public key to PEM format\n",
    "public_key_pem = public_key.public_bytes(\n",
    "    encoding=serialization.Encoding.PEM,\n",
    "    format=serialization.PublicFormat.SubjectPublicKeyInfo,\n",
    ")\n",
    "\n",
    "print(\"public key:\\n\", public_key)\n",
    "print(\"Private Key:\\n\", private_key_pem.decode())\n",
    "print(\"\\nPublic Key:\\n\", public_key_pem.decode())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5666cef3-9fd0-43b8-9461-7d1a82bcaa01",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Ciphertext: b\"~\\xb5a\\x9f2\\xeaRZ\\xfd\\x80\\x91\\xd8Xq\\xbe\\x9cH\\x81?29\\x14q\\x9e\\xbf:\\xdf\\xc5\\xba\\xe9'\\xa93\\xa4\\xf6\\xcd,\\xba;l \\xb4\\x88\\x9a\\xe9I\\x89\\x82\\xe1\\x13\\xc8\\xad\\xef\\xc91\\xa5\\x16-\\xadq\\xafhwF\\xf2/\\xa8\\x89\\xbc\\xc3\\xaf\\xf0\\xa03+yS`\\x97\\xcc\\x8a_5\\xe4/2$\\x98\\xda\\xea\\x8f\\r(\\xc25m\\x84@\\xe8{\\xe0\\xcf8\\xe3\\xf4F\\xcftNP\\xf9\\xab\\x07\\x00\\x19\\x9b\\r\\xfa\\x1c\\xaf%Q\\\\\\xab\\xc3\\x8f.\\xe3c=\\x05K55c\\xc9\\x00\\xa4\\xd6Y\\xbc\\xc2\\x90 \\xd0g%\\x9f\\xb3\\x97p\\xf7\\n\\xcb\\xa0\\xd9\\x05\\xa0\\xed\\xdd/\\xe3\\xd5\\xa0\\xa7.\\x1d\\xce[ \\xfc\\x11\\x88\\xac\\x11\\xa8\\x07\\x85\\x0e\\xcd\\xe0\\xcfb\\xf1Y7nF]n\\xaa\\x044M\\x9c\\x96\\x1cY-\\x19xC\\xcb\\xf7\\xc8\\xdd\\xca\\x02\\x1fW\\xca\\xbd\\x06\\xf9k\\x81\\x8c\\xb8\\xe7\\t\\xc3\\x9d\\xfe6db\\x9e\\x1eg\\xcaD\\xd4\\xe4x\\xaeJ\\xe9U\\xb2\\xfd5)>6B\\xe7\\x97\\xbe\\x14s}\\xa0}\\x9f\\x05\\xc2\"\n"
     ]
    }
   ],
   "source": [
    "from cryptography.hazmat.primitives import hashes\n",
    "from cryptography.hazmat.primitives.asymmetric import padding\n",
    "\n",
    "message = \"中午休息，This is a secret message.\".encode(\"utf-8\")\n",
    "\n",
    "# Encrypt the message using the public key\n",
    "ciphertext = public_key.encrypt(\n",
    "    message,\n",
    "    padding.OAEP(\n",
    "        mgf=padding.MGF1(algorithm=hashes.SHA256()),\n",
    "        algorithm=hashes.SHA256(),\n",
    "        label=None,\n",
    "    ),\n",
    ")\n",
    "\n",
    "print(\"\\nCiphertext:\", ciphertext)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "33f6bee5-ff45-46da-a121-30fff6c8c03f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Decrypted Plaintext: 中午休息，This is a secret message.\n"
     ]
    }
   ],
   "source": [
    "# Decrypt the ciphertext using the private key\n",
    "plaintext = private_key.decrypt(\n",
    "    ciphertext,\n",
    "    padding.OAEP(\n",
    "        mgf=padding.MGF1(algorithm=hashes.SHA256()),\n",
    "        algorithm=hashes.SHA256(),\n",
    "        label=None,\n",
    "    ),\n",
    ")\n",
    "\n",
    "print(\"\\nDecrypted Plaintext:\", plaintext.decode())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "d42239de-f90b-4883-abd0-1d1576849b4d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Ciphertext: 3c4a0f99b67967f8e1c1a2e8c105fde0bcf438772cd835dac2ecfe89fcb69f2e133e932e7103792cc08b629f686e6127367f73dd6cb694cc2021fb1b7bae73a2026ea294e49825eb41bf4b4c2deefc351dcddc0a4a4f5ca0b073c719cf4246b179a7a469b85a5de58a32c0e2e0cd09b73c39d2cef3509f269b27b9007c9ce6e4d4608a89099fab1c27a1811242b6d92411d3e0d790705c186406e74414b032c6d51c2debee180fcf8ab00cc73f227152482207f6fe72ea49d3fbf99a022b8c15beb6f6af675e5c1ae5b1e80ceb66a59fb4b22deaf31034660426121bc79a899bd00397f1ce67fb297672b753700c1326e7ab5d319f543c1dae29b35036c7ff5c\n",
      "\n",
      "Decrypted Plaintext: 中午休息，This is a secret message.\n"
     ]
    }
   ],
   "source": [
    "# 4. Encrypt the message using the public key and PKCS1_v1_5 padding\n",
    "ciphertext = public_key.encrypt(message, padding.PKCS1v15())\n",
    "print(\"\\nCiphertext:\", ciphertext.hex())\n",
    "# 5. Decrypt the message using the private key and PKCS1_v1_5 padding\n",
    "plaintext = private_key.decrypt(ciphertext, padding.PKCS1v15())\n",
    "print(\"\\nDecrypted Plaintext:\", plaintext.decode())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "a4a80bc7-1c02-46d5-9e1b-893ce2756401",
   "metadata": {},
   "outputs": [],
   "source": [
    "import base64\n",
    "import random\n",
    "import string\n",
    "\n",
    "\n",
    "def generate_random_string(length):\n",
    "    characters = string.ascii_letters + string.digits + string.punctuation\n",
    "    random_string = \"\".join(random.choice(characters) for i in range(length))\n",
    "    return random_string\n",
    "\n",
    "\n",
    "def encrypt_by_base64(data):\n",
    "    return base64.b64encode(data.encode(\"utf-8\"))\n",
    "\n",
    "\n",
    "# Example usage\n",
    "# random_str = generate_random_string(32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "e2407a1f-f07b-4f82-9182-555b5a6b1dd0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original string: U=~=SRwQvv?Gi8/iGXw(7UGbl>N#d\\K,\n",
      "Base64 encoded string: VT1+PVNSd1F2dj9HaTgvaUdYdyg3VUdibD5OI2RcSyw=\n"
     ]
    }
   ],
   "source": [
    "# The string to be encoded\n",
    "aesPassword = generate_random_string(32)\n",
    "\n",
    "# Encode the string to bytes using UTF-8 encoding\n",
    "# string_bytes = aesPassword.encode(\"utf-8\")\n",
    "\n",
    "# Perform Base64 encoding on the bytes\n",
    "# encryptAes = base64.b64encode(aesPassword.encode(\"utf-8\"))\n",
    "encryptAes = encrypt_by_base64(aesPassword)\n",
    "\n",
    "# Convert the resulting bytes back to a string for display (optional)\n",
    "encoded_string = encryptAes.decode(\"utf-8\")\n",
    "\n",
    "print(f\"Original string: {aesPassword}\")\n",
    "print(f\"Base64 encoded string: {encoded_string}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
